package com.postracker.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.postracker.dao.BasicDao;

public class BasicHibernateDaoImpl<T extends Serializable> implements
		BasicDao<T> {

	@Autowired
	private SessionFactory sessionFactory;

	private Class<T> daoClass;

	protected BasicHibernateDaoImpl(Class<T> daoClass) {
		this.daoClass = daoClass;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from " + daoClass.getName());
		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public T saveOrUpdate(T element) {
		return (T) sessionFactory.getCurrentSession().save(element);
	}

	@Override
	public void delete(T element) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"delete from " + daoClass.getName());
		query.executeUpdate();
	}
}
